//这个store用于控制element-plus控制菜单是否展开的collapse值和生成动态由菜单的数据
import {defineStore} from "pinia";
import {getMenuListApi} from "@/api/menu";
import type {RouteRecordRaw} from "vue-router";
import Layout from '@/layout/Index.vue'
import Center from "@/layout/center/Center.vue";

const modules = import.meta.glob('../../views/**/*.vue')

// 🟢 新增：默认菜单数据
const defaultMenuList = [{
    path: '/dashboard',
    component: 'Layout',
    name: 'dashboard',
    meta: {
        title: '看板',
        icon: 'House',
        roles: ['sys:dashboard']
    }
}]

// 🟢 新增：安全的 localStorage 读取函数
const getSafeMenuList = () => {
    try {
        const stored = localStorage.getItem('menuList')
        if (!stored) return defaultMenuList

        const parsed = JSON.parse(stored)
        return Array.isArray(parsed) ? parsed : defaultMenuList
    } catch (error) {
        console.error('解析菜单数据失败，使用默认菜单:', error)
        // 清除损坏的数据
        localStorage.removeItem('menuList')
        return defaultMenuList
    }
}

export const useMenuStore = defineStore("menuStore", {
    state: () => {
        return {
            collapse: false,
            menuList: getSafeMenuList(),
            // 🟢 新增：记录路由是否已初始化
            isRoutesInitialized: false
        }
    },
    getters: {
        getCollapse(state) {
            return state.collapse
        },
        getMenu(state) {
            return state.menuList
        }
    },
    actions: {
        setCollapse(collapse: boolean) {
            this.collapse = collapse
        },

        // 🟢 修改：添加路由前检查是否已初始化
        async getMenuList(router: any, userId: string) {
            if (this.isRoutesInitialized) {
                console.log('路由已初始化，跳过重复添加')
                return this.menuList
            }

            return new Promise((resolve, reject) => {
                getMenuListApi(userId).then((res) => {
                    let accessRoute;
                    if (res && res.code == 200) {
                        // 🟢 先清除可能存在的重复路由
                        this.clearExistingRoutes(router, res.data)

                        //生成路由
                        accessRoute = generateRoute(res.data, router) as any
                        this.menuList = defaultMenuList.concat(accessRoute)

                        // 🟢 标记为已初始化
                        this.isRoutesInitialized = true

                        try {
                            localStorage.setItem('menuList', JSON.stringify(this.menuList))
                        } catch (error) {
                            console.error('保存菜单数据失败:', error)
                        }
                    }
                    resolve(this.menuList)
                }).catch((error) => {
                    reject((error))
                })
            })
        },
        // 🟢 新增：清除已存在的路由
        clearExistingRoutes(router: any, routes: any[]) {
            routes.forEach((route: any) => {
                if (route.name) {
                    const existingRoute = router.getRoutes().find((r: any) => r.name === route.name)
                    if (existingRoute) {
                        router.removeRoute(route.name)
                        console.log(`移除重复路由: ${route.name}`)
                    }
                }
                // 递归处理子路由
                if (route.children && route.children.length > 0) {
                    this.clearExistingRoutes(router, route.children)
                }
            })
        },
        // 🟢 修改刷新方法，重置初始化状态
        async refreshMenuList(router: any, userId: string) {
            try {
                // 🟢 重置初始化状态
                this.isRoutesInitialized = false
                const res = await getMenuListApi(userId)
                if (res && res.code == 200) {
                    // 清除现有路由
                    this.clearExistingRoutes(router, res.data)
                    // 重新生成
                    const accessRoute = generateRoute(res.data, router) as any
                    this.menuList = defaultMenuList.concat(accessRoute)
                    this.isRoutesInitialized = true

                    try {
                        localStorage.setItem('menuList', JSON.stringify(this.menuList))
                    } catch (error) {
                        console.error('保存菜单数据失败:', error)
                    }
                    return this.menuList
                }
            } catch (error) {
                console.error('刷新菜单失败:', error)
                throw error
            }
        },
        // 🟢 修改清除方法，重置初始化状态
        clearMenu() {
            this.menuList = defaultMenuList
            this.isRoutesInitialized = false
            try {
                localStorage.removeItem('menuList')
            } catch (error) {
                console.error('清除菜单数据失败:', error)
            }
        }
    },
})

//动态生成路由（保持不变）
export function generateRoute(routes: RouteRecordRaw[], router: any) {
    //路由数据容器
    const res: Array<RouteRecordRaw> = []
    routes.forEach((route: any) => {
        const tmp = {...route}
        const component = tmp.component
        if (route.component) {
            if (component == 'Layout') {
                tmp.component = Layout
            } else {
                tmp.component = modules[`../../${component}`]
            }
        }
        //有下级
        if (tmp.children && tmp.children.length > 0) {
            if (route.component != 'Layout') {
                tmp.children = Center
            }
            //递归：生成下级
            tmp.children = generateRoute(tmp.children, router)
        }
        res.push(tmp)
        //加入路由
        router.addRoute(tmp)
    })
    return res
}